const Promise = require('bluebird');
const axios = require('axios');
const schedule = require('node-schedule');

module.exports = function (storage, config) {
    let {modelsData: {Goodses, CaptureLogs}} = storage, {captureHosts, webservice_key} = config;

    /**
     * 获取最新商品
     */
    let captureNewLastData = {};
    let captureNew = function () {
        let method = 'findNew';
        let captureRquest = function (action, page) {
            let host = captureHosts[Math.floor(Math.random() * captureHosts.length)];
            return axios.post(host + '/api/webservice/v1/capture/single?key=' + webservice_key + '&action=' + action + '&method=' + method, {page: page || 1}).then(function (response) {
                let data = response.data;
                data.source = action;
                return data;
            }).catch(function (err) {
                if (err) {
                    console.error('\n', err.stack || err.message);
                }
                return {success: false};
            });
        };
        return Promise.props({
            qingtaoke: captureRquest('qingtaoke', 1),
            yishoudan: captureRquest('yishoudan', 1),
            dataoke: captureRquest('dataoke', 1),
            taokezhushou: captureRquest('taokezhushou', 1)
        }).then(function (results) {
            let goodses = [];
            let captureNewNewMap = {}, total_count = 0, noexist = 0, add_count = 0, update_count = 0, sources = [],
                ext_data = {};
            for (let i in results) {
                let item = results[i];
                if (item.success) {
                    let rows = item.data;
                    sources.push(i);
                    ext_data[i + '_count'] = rows.length;
                    total_count += rows.length;

                    let sourceNoexist = 0;
                    for (let j in rows) {
                        let row = rows[j];
                        captureNewNewMap[row.auctionId] = true;
                        if (!captureNewLastData[row.auctionId]) {
                            noexist++;
                            sourceNoexist++;
                            row.source = i;
                            row.ext_data = JSON.stringify(row);
                            goodses.push(row);
                        }
                    }
                    ext_data[i + '_noexist'] = sourceNoexist;
                }
            }
            captureNewLastData = captureNewNewMap;

            Promise.mapSeries(goodses, function (goods) {
                if(!goods.auctionId || !goods.title){
                    return;
                }
                return Goodses.findOne({where: {auctionId: goods.auctionId}}).then(function (oldGoods) {
                    if (!oldGoods) {
                        add_count++;
                        return Goodses.create(goods);
                    }
                });
            }).then(function () {
                let captureLog = {
                    total_count: total_count,
                    noexist: noexist,
                    add_count: add_count,
                    update_count: update_count,
                    type: 'new',
                    sources: sources.join(','),
                    ext_data: JSON.stringify(ext_data)
                };
                return CaptureLogs.create(captureLog);
            });
            return {success: true};
        });
    }

    /**
     * 获取人气优惠劵
     */
    let captureRenqiLastData = {};
    let captureRenqi = function () {
        Goodses.updateOrderBy();

        let method = 'findRenqi';
        let captureRquest = function (action, page) {
            let host = captureHosts[Math.floor(Math.random() * captureHosts.length)];
            return axios.post(host + '/api/webservice/v1/capture/single?key=' + webservice_key + '&action=' + action + '&method=' + method, {page: page || 1}).then(function (response) {
                let data = response.data;
                data.source = action;
                return data;
            }).catch(function (err) {
                if (err) {
                    console.error('\n', err.stack || err.message);
                }
                return {success: false};
            });
        };
        return Promise.props({
            qingtaoke: captureRquest('qingtaoke', 1),
            yishoudan: captureRquest('yishoudan', 1),
            dataoke: captureRquest('dataoke', 1),
            taokezhushou: captureRquest('taokezhushou', 1)
        }).then(function (results) {
            let goodses = [];
            let captureRenqiNewData = {}, total_count = 0, noexist = 0, add_count = 0, update_count = 0, sources = [],
                ext_data = {};
            for (let i in results) {
                let item = results[i];
                if (item.success) {
                    let rows = item.data;
                    sources.push(i);
                    ext_data[i + '_count'] = rows.length;
                    total_count += rows.length;

                    let sourceNoexist = 0;
                    for (let j in rows) {
                        let row = rows[j];
                        captureRenqiNewData[row.auctionId] = true;
                        if (!captureRenqiLastData[row.auctionId]) {
                            noexist++;
                            sourceNoexist++;
                            row.order_by = 1000000 - j;
                            row.source = i;
                            row.ext_data = JSON.stringify(row);
                            goodses.push(row);
                        }
                    }
                    ext_data[i + '_noexist'] = sourceNoexist;
                }
            }
            captureRenqiLastData = captureRenqiNewData;

            Promise.mapSeries(goodses, function (goods) {
                if(!goods.auctionId || !goods.title){
                  return;
                }
                return Goodses.findOne({where: {auctionId: goods.auctionId}}).then(function (oldGoods) {
                    if (!oldGoods) {
                        add_count++;
                        return Goodses.create(goods);
                    } else {
                        update_count++;
                        return Goodses.update({order_by: goods.order_by}, {where: {auctionId: goods.auctionId}});
                    }
                });
            }).then(function () {
                let captureLog = {
                    total_count: total_count,
                    noexist: noexist,
                    add_count: add_count,
                    update_count: update_count,
                    type: 'renqi',
                    sources: sources.join(','),
                    ext_data: JSON.stringify(ext_data)
                };
                return CaptureLogs.create(captureLog);
            });
            return {success: true};
        });
    }

    /**
     * 十五分钟获取一次最新优惠劵
     */
    schedule.scheduleJob('45 */10 * * * *', captureNew);
    //setInterval(captureNew, 1000 * 60 * 15);

    /**
     * 一小时获取一次人气领券
     */
    schedule.scheduleJob('0 0 * * * *', captureRenqi);
    //setInterval(captureRenqi, 1000 * 60 * 90);

    return {
        captureNew: captureNew,
        captureRenqi: captureRenqi
    }
};